package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.AccessLinkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.menu.enums.MarketManagementMenuEnum;
import com.xbongbong.pro.script.pojo.dto.DuplicateDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.sys.domain.entity.CoverRoleEntity;
import com.xbongbong.sys.domain.entity.RoleEntity;
import com.xbongbong.sys.model.CompanyModel;
import com.xbongbong.sys.model.CoverRoleModel;
import com.xbongbong.sys.model.RoleModel;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Created with IntelliJ IDEA
 *
 * @Auther: 宋港迎
 * @Date: 2021/04/15/15:14
 * @Destription:
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/clue")
public class ClueScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(FundScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;

    @Resource
    private CompanyModel companyModel;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private RoleModel roleModel;
    @Resource
    private CoverRoleModel coverRoleModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    /**
     * 老公司插入线索查重按钮
     * @param duplicateDTO
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/initClueDuplicate", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initClueDuplicate(@RequestBody @Valid DuplicateDTO duplicateDTO) throws Exception {
        try {
            if (!proBaseConfig.getXbbCode().equals(duplicateDTO.getXbbCode())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
            }
            long timeStart = DateTimeUtil.getInt();
            List<String> corpIdList = duplicateDTO.getCorpidList();
            if (CollectionsUtil.isEmpty(corpIdList)) {
                corpIdList = companyModel.getCorpidList();
            }
            if (corpIdList == null) {
                return "";
            }
            LOG.info("共有" + corpIdList.size() + "家数据");
            int i = 0;
            List<PaasMenuEntity> paasMenuEntityList = new ArrayList<>();
            for (String corpid : corpIdList) {
                i++;
                LOG.info("现在是第" + i + "家公司");
                PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.CLUE.getAlias(), corpid);
                if (Objects.nonNull(paasMenuEntity)){
                    PaasMenuEntity duplicatePaasMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.CLUE_DUPLICATE.getAlias(), corpid);
                    if (Objects.nonNull(duplicatePaasMenuEntity)){
                        //说明当前公司已经有了线索查重按钮，则不再进行插入
                        continue;
                    }
                    //查找当前sort的最大数
                    Integer sort = paasMenuModel.maxSortInSubMenu(corpid, paasMenuEntity.getId(), DelEnum.NORMAL.getDel());
                    PaasMenuEntity paasMenuEntityInsert = new PaasMenuEntity();
                    paasMenuEntityInsert.setCorpid(corpid);
                    paasMenuEntityInsert.setAppId(paasMenuEntity.getAppId());
                    paasMenuEntityInsert.setParentId(paasMenuEntity.getId());
                    paasMenuEntityInsert.setName(XbbRefTypeEnum.CLUE_DUPLICATE.getName());
//                    paasMenuEntityInsert.setNameEn(XbbRefTypeEnum.CLUE_DUPLICATE.getName());
                    paasMenuEntityInsert.setIcon(AccessLinkEnum.CLUE_DUPLICATE.getIcon());
                    paasMenuEntityInsert.setColor(AccessLinkEnum.CLUE_DUPLICATE.getColor());
                    if (Objects.isNull(sort)) {
                        sort = 0;
                    }
                    paasMenuEntityInsert.setSort(sort + 1);
                    paasMenuEntityInsert.setType(MarketManagementMenuEnum.CLUE_DUPLICATE.getType());
                    paasMenuEntityInsert.setCreatorId(paasMenuEntity.getCreatorId());
                    long now = DateUtil.getInt();
                    paasMenuEntityInsert.setAddTime(now);
                    paasMenuEntityInsert.setUpdateTime(now);
                    paasMenuEntityInsert.setDel(DelEnum.NORMAL.getDel());
                    paasMenuEntityInsert.setSaasMark(paasMenuEntity.getSaasMark());
                    paasMenuEntityInsert.setEnable(paasMenuEntity.getEnable());
                    paasMenuEntityInsert.setAlias(XbbRefTypeEnum.CLUE_DUPLICATE.getAlias());
                    paasMenuEntityInsert.setMobileUrl(AccessLinkEnum.CLUE_DUPLICATE.getMobileUrl());
                    paasMenuEntityInsert.setDistributorMark(BasicConstant.ZERO);
                    paasMenuEntityList.add(paasMenuEntityInsert);
                }
            }
            //插入数据库
            paasMenuModel.insertBatch(paasMenuEntityList);
            LOG.warn("-----------time consume initClueDuplicate:" + (DateTimeUtil.getInt() - timeStart));
            LOG.warn("-----------老公司插入线索查重按钮执行完毕-----------");
        } catch (Exception e) {
            LOG.error("initClueDuplicate", e);
        }
        return JSON.toJSONString("{\"msg\":\"success\"}");
    }

    /**
     * 新增线索转客户权限  给老数据中有   线索表单“查看”权限的和有客户管理表单“新建”权限的客户
     * date: 2022/7/14 2:00 下午
     * @author yingjf
     * @param :
     */
    @RequestMapping(value = "/dealTransCustomer", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String dealTransCustomer(@RequestBody @Valid DuplicateDTO duplicateDTO)throws XbbException{
        LOG.warn("---------------- 开始处理线索转客户老公司权限 -------------------");
        long start = DateTimeUtil.getInt();
        // 成功数
        Integer successNum = 0;
        // 不更新公司数
        Integer notUpdateNum = 0;
        // 如果没传公司ID就取所有公司
        List<String> corpidList = CollectionUtils.isNotEmpty(duplicateDTO.getCorpidList()) ? duplicateDTO.getCorpidList() : companyModel.getCorpidList();
        int i = 1;
        //更新失败公司ID集合
        Set<String> errorCorpidList = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del",0);
        param.put("columns","id, permissions");
        for (String corpid : corpidList) {
            int x = corpidList.size() - i;
            LOG.info("-----------------------------当前是第" + i + "家公司,还有" + x + "家是公司需要刷--------------------------");
            i++;
            try {
                //获取公司全部角色
                param.put("corpid",corpid);
                //自定义权限
                List<RoleEntity> roleEntityList = roleModel.findAllRoleByCorpid(param);
                //系统权限
                List<CoverRoleEntity> coverRoleEntityList = coverRoleModel.findEntitys(param);
                List<RoleEntity> updateRoleEntity = new ArrayList<>();
                roleEntityList.forEach(roleEnt -> {
                    String permissions = setRolePermissions(roleEnt.getPermissions());
                    if (!Objects.equals(permissions, roleEnt.getPermissions())){
                        RoleEntity roleEntity = new RoleEntity();
                        roleEntity.setId(roleEnt.getId());
                        roleEntity.setPermissions(permissions);
                        updateRoleEntity.add(roleEntity);
                    }
                });
                List<CoverRoleEntity> updateCoverRoleEntity = new ArrayList<>();
                coverRoleEntityList.forEach(coverRoleEnt -> {
                    String permissions = setRolePermissions(coverRoleEnt.getPermissions());
                    if (!Objects.equals(permissions, coverRoleEnt.getPermissions())){
                        CoverRoleEntity coverRoleEntity = new CoverRoleEntity();
                        coverRoleEntity.setId(coverRoleEnt.getId());
                        coverRoleEntity.setPermissions(permissions);
                        updateCoverRoleEntity.add(coverRoleEntity);
                    }
                });
                if (CollectionsUtil.isNotEmpty(updateRoleEntity)){
                    roleModel.updateBatchPermissions(updateRoleEntity, corpid);
                }
                if (CollectionsUtil.isNotEmpty(updateCoverRoleEntity)){
                    coverRoleModel.updateBatchPermissions(updateCoverRoleEntity, corpid);
                }
                if (updateRoleEntity.isEmpty() && updateCoverRoleEntity.isEmpty()){
                    notUpdateNum++;
                }else {
                    successNum++;
                }
            } catch (Exception e) {
                LOG.error("公司编号为:" + corpid + "更新失败,失败理由是", e);
                errorCorpidList.add(corpid);
            }
        }
        LOG.error("更新失败公司ID集合" + errorCorpidList.toString());
        LOG.warn("不更新公司数为:" + notUpdateNum);
        LOG.warn("consume:" + (DateTimeUtil.getInt() - start));
        LOG.warn("更新菜单表中数据操作成功,本次共更新了[{}]家公司数据", successNum);
        JSONObject object = new JSONObject();
        object.put("success", "成功");
        return object.toJSONString();
    }

    /**
     * 添加转换客户权限
     * @param permissions
     * @return
     */
    public String setRolePermissions(String permissions){
        StringBuilder stringBuilder = new StringBuilder(permissions);
        List<String> permissionsId = Arrays.asList(permissions.split("\\|"));

        // 40客户新建
        // 644线索查询
        // 1310转换客户
        if (permissionsId.contains("40") && permissionsId.contains("644")&&!permissionsId.contains("1310")){
            permissions = stringBuilder.append("1310|").toString();
        }
        return permissions;
    }
}
